/**
 * 拖拽状态
 */
var DragState;
(function (DragState) {
    DragState["BeforeDrag"] = "beforeDrag";
    DragState["AfterDrag"] = "afterDrag"; // 已被拖出
})(DragState || (DragState = {}));
/**
 * 消息类型
 */
var MessageType;
(function (MessageType) {
    MessageType["DragEnd"] = "dragEnd";
    MessageType["GetConfig"] = "getConfig";
    MessageType["DeleteDraged"] = "deleteDraged";
    MessageType["DragStateChange"] = "dragStateChange";
})(MessageType || (MessageType = {}));
var config = JSON.parse(localStorage.getItem('dragMsgConfig'));
var framePath = config.framePath;
var appId = config.id;
var components;
var initConfig = {
    init: function () {
        window.parent.postMessage({
            type: MessageType.GetConfig,
            appId: appId,
        }, framePath);
    }
};
var dragMsg = {
    componentIdList: null,
    /**
     * 初始化插件
     * @param componentIdList {Array<string>} 当前页面需要拖拽的组件id列表
     */
    init: function (componentIdList) {
        frameMsg.init();
        initConfig.init();
        this.componentIdList = componentIdList;
    },
    /**
     * 应用发送消息给组件
     * @param componentId {string} 组件元素id
     * @param content 消息内容
     */
    sendMsg2Component: function (_a) {
        var elementId = _a.componentId, content = _a.content;
        var componentDragState = tools.$(elementId).getAttribute('data-drag-state');
        // 根据组件状态判断是发送给自己还是拖拽到其他窗口的组件
        if (componentDragState === DragState.AfterDrag) {
            // console.log(componentId, '已拖出');
            window.parent.postMessage({
                type: 'app2DrapedComponent',
                id: components.find(function (value) { return value.elementId === elementId; }).id,
                content: content
            }, framePath);
        }
        if (componentDragState === DragState.BeforeDrag) {
            // console.log(componentId, '未拖出');
            var iframe = tools.$(elementId + 'iframe');
            iframe.contentWindow.postMessage(content, '*');
        }
    }
};
var tools = {
    $: function (id) {
        return document.getElementById(id);
    },
    on: function (el, type, listener) {
        el.addEventListener(type, listener);
    },
    addClass: function (el, className) {
        el.classList.add(className);
    },
    removeClass: function (el, cls) {
        if (arguments.length < 2) {
            el.classList.remove(cls[0]);
        }
        else {
            for (var i = 1, len = arguments.length; i < len; i++) {
                el.classList.remove(arguments[i]);
            }
        }
    }
};
var drag = {
    initDragItem: function (elementId) {
        var comp = components.find(function (component) { return component.elementId === elementId; });
        // 确保组件有配置到权限系统，才对元素进行初始化拖拽和通信
        if (comp === undefined)
            return;
        var el = tools.$(elementId);
        el.setAttribute('draggable', 'true');
        // 添加拖拽区域的iframe的id值为组件id+'iframe'
        var iframeNode = el.getElementsByTagName('iframe')[0];
        if (iframeNode === undefined) {
            throw new Error('拖拽区域内未检测到iframe节点，将导致消息发送功能无法正常使用');
        }
        else {
            iframeNode.setAttribute('id', elementId + 'iframe');
        }
        tools.on(el, 'dragstart', this.handleDragStart);
        tools.on(el, 'dragend', this.handleDragEnd);
        if (comp.dragState === DragState.BeforeDrag) {
            el.setAttribute('data-drag-state', DragState.BeforeDrag);
        }
        else {
            el.setAttribute('data-drag-state', DragState.AfterDrag);
            el.hidden = true;
        }
    },
    handleDragStart: function (ev) {
        var el = ev.target;
        tools.addClass(el, 'dragging');
        var elementId = el.getAttribute('id');
        var component = components.find(function (c) { return c.elementId === elementId; });
        ev.dataTransfer.setData('text', JSON.stringify({
            componentId: component.id,
            from: 'app'
        }));
    },
    handleDragEnd: function (ev) {
        var el = ev.target;
        tools.removeClass(el, ['dragging']);
        ev.preventDefault();
        if (ev.stopPropagation) {
            ev.stopPropagation();
        }
        return false;
    },
    init: function (componentIdList) {
        var _this = this;
        componentIdList.forEach(function (componentId) {
            _this.initDragItem(componentId);
        });
    },
};
var frameMsg = {
    receiveParentMsg: function (ev) {
        // 接收父级消息，如果类型是getConfig，则设置app配置,然后初始化拖拽
        if (ev.data.type === MessageType.GetConfig) {
            // console.log('GetConfig');
            components = ev.data.components;
            drag.init(dragMsg.componentIdList);
        }
        // 接收父级消息，如果类型是dragEnd， 则隐藏组件
        if (ev.data.type === MessageType.DragEnd) {
            var el = tools.$(ev.data.elementId);
            el.hidden = true;
            el.setAttribute('data-drag-state', DragState.AfterDrag);
        }
        // 接收父级消息，如果类型是DeleteDraged，则显示组件
        if (ev.data.type === MessageType.DeleteDraged) {
            var el = tools.$(ev.data.elementId);
            el.hidden = false;
            el.setAttribute('data-drag-state', DragState.BeforeDrag);
        }
        // 组件状态拖拽状态批量改变
        if (ev.data.type === MessageType.DragStateChange) {
            ev.data.components.forEach(function (v) {
                var el = tools.$(v.elementId);
                el.hidden = v.dragState === DragState.AfterDrag;
                el.setAttribute('data-drag-state', v.dragState);
            });
        }
    },
    init: function () {
        window.addEventListener('message', this.receiveParentMsg);
    },
};
